import { ref, reactive } from 'vue';
import type { ResponseData } from '../utils/request';

/**
 * 请求状态钩子函数
 * @param requestFn 请求函数
 * @param defaultData 默认数据
 * @param immediate 是否立即执行
 * @param initialParams 初始参数
 */
export default function useRequest<T = any, P extends any[] = any[]>(
  requestFn: (...args: P) => Promise<ResponseData<T>>,
  defaultData?: T,
  immediate: boolean = false,
  initialParams?: P
) {
  // 加载状态
  const loading = ref(false);
  
  // 错误信息
  const error = ref<Error | null>(null);
  
  // 响应数据
  const data = ref<T | undefined>(defaultData);
  
  // 响应对象
  const response = ref<ResponseData<T> | null>(null);
  
  // 是否已执行过请求
  const called = ref(false);
  
  // 执行请求
  const run = async (...args: P): Promise<ResponseData<T>> => {
    loading.value = true;
    error.value = null;
    called.value = true;
    
    try {
      const res = await requestFn(...args);
      response.value = res;
      data.value = res.data;
      return res;
    } catch (err) {
      error.value = err as Error;
      throw err;
    } finally {
      loading.value = false;
    }
  };
  
  // 重置状态
  const reset = () => {
    loading.value = false;
    error.value = null;
    data.value = defaultData;
    response.value = null;
    called.value = false;
  };
  
  // 如果需要立即执行
  if (immediate && initialParams) {
    run(...initialParams);
  }
  
  return {
    loading,
    error,
    data,
    response,
    called,
    run,
    reset
  };
} 